<template>
    <div class="app-container">
        <div class="table-info-row">
            <!-- font-weight-blod -->
            <div class="table-info font-size-20  color-666">
                <div>桌台：{{ tableInfo.roomName }}
                    <span class="font-size-16 font-weight-normal">（转台前桌号：{{ tableInfo.beforeRoomName ?
                        tableInfo.beforeRoomName : '--' }}）</span>
                </div>
                <div>单号：{{ tableInfo.consumeCode }} </div>
                <div>人数：{{ tableInfo.peopleCount }}人 </div>
                <div>开台时间：{{ tableInfo.openTime }} </div>
                <!-- ls.get('WARES_ORDER') 购物车有没有数据 直接来到结账页面 -->
                <div >出品方式：{{ ls.get('WARES_ORDER') ? '先买单' : tableInfo.prodMethod }} </div>
                <div class="color-FF3333">低消：{{ tableInfo.minConsume }} </div>
            </div>
            <el-button class="back-btn" @click="confirmClose" v-if="received > 0">关闭</el-button>
            <el-button class="back-btn" @click="handleClose" v-else>关闭</el-button>
        </div>
        <div class="content-box">
            <Wares ref="WaresRef" :waresData="waresData" :saleData="saleData" :payData="payData" :price="price"
                :vipPrice="vipPrice" @emitPaySuccess="emitPaySuccess" />
            <Bill :saleData="saleData" :payData="payData" :price="price" :vipPrice="vipPrice" :receive="receive"
                :received="received" :unpay="unpay" :vipInfo="vipInfo" :tableInfo="tableInfo" :bookAmtForm='bookAmtForm'
                @returnPayType12="returnPayType12" /> 
            <Payment ref="PaymentRef" :marketUser="marketUser" :marketUserName="marketUserName" :hasPay="hasPay" :minConsume="minConsume" :price="price" :vipPrice="vipPrice" :receive="receive" :received="received"
                :saleData="saleData" :payData="payData" :unpay="unpay" :tableInfo="tableInfo" :vipInfo="vipInfo"
                :selectWares="multipleSelection" :coinsPrice="coinsPrice" :bookAmtForm='bookAmtForm' @emitSubmit="emitSubmit" />
        </div>
    </div>
    <ZDialog v-model="confirmShow" width="60%" title="提示" content="尚未结账，确认要关闭吗？" @cancel="confirmShow = false" @confirm="handleClose"></ZDialog>
</template>

<script setup >
import { formatDecimal } from '@/utils/chenhao'
import { getLocalIPv4 } from "@/utils/getip.js";
import Wares from './components/wares.vue'
import Bill from './components/bill.vue'
import Payment from './components/payment.vue'
import Api from '@/api'
import ls from '@/lib/ls'
import ZDialog from '@/components/Dialog/Dialog.vue'
import useConfigStore from '@/store/config'
const configStore = useConfigStore()
//获取ip地址
const ip = ref("");
getLocalIPv4()
    .then((ipAddress) => {
        // 在这里处理获取到的 IP 地址
        ip.value = ipAddress;
        console.log("IP 地址:", ip.value);
    })
    .catch((error) => {
        console.error("发生错误:", error);
        // 在这里处理错误情况
    });
const vipInfo = ref({
    hasVipPrice: false,
    priceType: '1',
    isDiscountSharing: []
})
// -------------------------------未结账商品模块-------------------------
// 商品列表
const router = useRouter()
let tableInfo = ref({})
let waresData = ref([])
const WaresRef = ref()
waresData.value = ls.get('WARES_ORDER') || []
console.log('waresData :>> ', ls.get('WARES_ORDER'));
const getWaresData = () => {
    const consumeCode = router.currentRoute.value.query.consumeCode  // 台单号
    // 获取路由的payBatchCode，如果没有就从ls缓存获取
    let payBatchCode = router.currentRoute.value.query.payBatchCode // 结账单号
    if (!payBatchCode) {
        payBatchCode = ls.get('payBatchCode')
    }
    console.log('路由获取的 台单号 consumeCode :>> ', consumeCode);
    console.log('路由获取的 结账单号 payBatchCode :>> ', payBatchCode);
    let data = {
        consumeCode,
        payBatchCode,
        pageSize:'999'
    }
    Api.Common.PcObjProcess.Do({ "functionName": "GetPayBatchGoodsList", "orgCode": "0004", "contentData": data }).then(res => {
        res = res.result[0]
        console.log('获取结账总信息 res 1111111111111111:>> ', res);
        tableInfo.value = { ...res }
        // 判断是否有ls缓存 有的话就是下单页面点结账来的
        if (waresData.value && waresData.value.length > 0) {
            tableInfo.value.prodMethod = '先买单'
            waresData.value = waresData.value.map(item => {
                return {
                    ...item,
                    jg: item.orderQty * item.salePrice,
                    vip_jg: item.orderQty * item.vipPrice,
                }
            })
        } else {
            ls.set('payTableInfo', tableInfo.value)
            waresData.value = []
            // 菜品的itemcode
            let detailList = []
            res.consumeList.forEach(item => {
                if (item.state == '未支付' || item.state == '支付中') {
                    detailList.push(item.itemCode)
                    waresData.value.push({
                        ...item,
                        jg: item.orderQty * item.salePrice,
                        vip_jg: item.orderQty * item.vipPrice,
                    })
                }
            })
            saleData.value = res.serviceList.map(item => {
                return {
                    ...item,
                    yhxm: item.type,
                    je: item.amt,
                }
            })
            console.log(res.payList);
            
            payData.value = res.payList.map(item => {
                if(item.payTypeName == '现金' && item.giveChange > 0){
                    return {
                        ...item,
                        payAmt: item.realAmt,
                        zffs: item.payTypeName,
                        skje: Number(formatDecimal(item.realAmt - item.giveChange)),
                        detailList,
                    }
                }else{
                    return {
                        ...item,
                        payAmt: item.realAmt,
                        zffs: item.payTypeName,
                        skje: item.realAmt,
                        detailList,
                    }
                }
                
            })
            // 重置选择的商品
            // setTimeout(() => {
            //     console.log('WaresRef :>> ', WaresRef);
            //     WaresRef.value.handleSelectionChange([])
            // },1000)
        }
    })
}
getWaresData()

// 子组建选择商品后调用赋值
let multipleSelection = ref([])
const emitPaySuccess = (v) => {
    multipleSelection.value = v
    console.log('多选 multipleSelection.value :>> ', multipleSelection.value);
}


// -------------------------------应付金额模块-------------------------
// 优惠项目列表
let saleData = ref([])
// 支付方式列表
let payData = ref([])

// --------------------------------------------计算属性---------------------------------------
// -------------------计算总价----------------
const price = computed(() => {
    return multipleSelection.value.reduce((acc, cur) => {
        return formatDecimal((+acc) + (+cur.jg))
    }, '0')
})
// -------------------计算VIP价格----------------
const vipPrice = computed(() => {
    return multipleSelection.value.reduce((acc, cur) => {
        return formatDecimal((+acc) + (+cur.vip_jg))
    }, '0')
})
// -------------------计算可用金币价格----------------
const coinsPrice = computed(() => {
    // 金币抵扣部分
    // return multipleSelection.value.reduce((acc, cur) => {
    //     return formatDecimal((+acc) + (+cur.saleCoins))
    // }, '0')
    // 金币抵扣全部 
    return multipleSelection.value.reduce((acc, cur) => {
        if (vipInfo.value.hasVipPrice && cur.isUseGold == '1') {
            return formatDecimal((+acc) + (+cur.vipPrice) * Number(cur.orderQty))
        } else if (!vipInfo.value.hasVipPrice && cur.isUseGold == '1') {
            return formatDecimal((+acc) + (+cur.salePrice) * Number(cur.orderQty))
        } else {
            return formatDecimal((+acc) + 0)
        }
    }, '0')
})
// console.log('coinsPrice :>> ', coinsPrice.value);
// ------------------计算应收------------------
const receive = computed(() => {
    let num = ""
    // console.log('num :>> ', num);
    if (vipInfo.value.priceType == '2') {
        num = vipPrice.value
    } else {
        num = price.value
    }
    saleData.value.forEach(item => {
        if (item.yhxm != '会员折扣优惠') {
            if (item.yhxm == '服务费' || item.yhxm == '补低消') {
                // 判断是服务费就加钱
                num = (+num) + (+item.je)
                // console.log('item.je :>> ', num + item.je);
            } else {
                // 其他就减
                num -= (+item.je)
            }
        }
    });
    return formatDecimal(num)
})
// ----------------计算已收------------------
const received = computed(() => {
   
    // 计算已收金额
    const totalReceived = payData.value.reduce((acc, cur) => {
        return formatDecimal((+acc) + (+cur.skje))
    }, '0')

    // 加上 预订押金
    const additionalAmount = +bookAmtForm.value.bookAmt || 0;
    return formatDecimal(+totalReceived + additionalAmount)
})

// ----------------计算还需收款------------------
const unpay = computed(() => {
    return formatDecimal(receive.value - received.value) > 0 ? formatDecimal(receive.value - received.value) : '0'
})

// 子组件点击结账
const emitSubmit = () => {
    getWaresData()
}
const hasPay = ref(0)
const minConsume = ref(0)
const tableConsumeCode = ref('')
const marketUserName = ref('')
const marketUser = ref('')
onMounted(() => {
    // 初始化支付开关
    configStore.payFlag = false; 

    tableConsumeCode.value = router.currentRoute.value.query.consumeCode
    marketUserName.value = router.currentRoute.value.query.marketUserName
    marketUser.value = router.currentRoute.value.query.marketUser

    Api.Common.PcObjProcess.Do({ "functionName": "LockConsumeCode", "contentData": { consumeCode: tableConsumeCode.value } })
        .then(res => {
            console.log(res);
        })
        .catch(err => {
            router.back()
        })

    getBookAmt()
})
onUnmounted(() => {
    Api.Common.PcObjProcess.Do({ "functionName": "UnLockConsumeCode", "contentData": { consumeCode: tableConsumeCode.value } }).then(res => {
        console.log(res);
    })
    // window.removeEventListener('keydown', func1)
    ls.remove('WARES_ORDER')
    ls.remove('payBatchCode')
    ls.remove('payTableInfo')
    ls.remove('ISPAY_FIRST') // 先买单标记
})
const bookAmtForm = ref({
    bookAmt : 0,
    toolBookAmt: 0,
    bookPayType : '',
    bookCardNo : '',
    bookTradeNo : ''
})
const getBookAmt = async()=>{
// 预订押金
await Api.Common.PcObjProcess.Do({ "functionName": "GetRoomReserveState", "contentData": {roomCode:ls.get('TABLE_INFO').roomCode} })
    .then(res => {
        
        if(!res.isUseReserveAmt && res.reserveAmt > 0){ //true 已抵扣 false 未抵扣  false可以用
          bookAmtForm.value.bookAmt = res.reserveAmt
          bookAmtForm.value.toolBookAmt = res.reserveAmt
          bookAmtForm.value.bookPayType = res.posPayType
          bookAmtForm.value.bookCardNo = res.cardNo
          bookAmtForm.value.bookTradeNo = res.tradeNo
          console.log('有押金',res);
        
          // this.data.carPrice = this.data.carPrice - res.reserveAmt
        }else{
            bookAmtForm.value.bookAmt = 0
            bookAmtForm.value.toolBookAmt = 0
        }
    })
    .catch(err=>{
    })
}
// 点击关闭
const PaymentRef = ref()
const confirmShow = ref(false) // 确认弹窗
const confirmClose = ()=>{
    confirmShow.value = true
    console.log(received.value);
    
}
console.log(router.currentRoute.value.query);
const loss = ref(router.currentRoute.value.query.loss)

// 检测是否有赠送的支付方式,有的或撤销赠送
const  checkAndLogPayData = async()=> {
    console.log(payData.value);
    
    let result = payData.value.find(item => item.payType == "011");
    console.log(result);
    
    if(result){
        const data = {
            payType: result.payType,
            itemCode: result.itemCode,
            amt: result.payAmt,
            payBatchCode: result.payBatchCode,
            consumeCode: result.consumeCode,
            cardNo: result.cardNo,
            tradeNo: result.tradeNo,
        }
        await Api.Common.PcObjProcess.Do({ "functionName": "OrderPayRet", "orgCode": "0004", "contentData": { ...data, "ip": ip.value } })
        .then(res => {
            payData.value = payData.value.filter(item => item.payType != "011");  
            
        })
        .catch(err=>{
            ElNotification({
                title: '提示',
                message: '撤销失败',
                type: 'error',
            })
        })
    }
}
const handleClose =  async(params) => { 
    console.log(tableInfo.value.prodMethod);
    console.log(payData.value);
    console.log(waresData.value);
    console.log(loss.value);
    
    await checkAndLogPayData() // 如果有赠送 撤销赠送
    // if (tableInfo.value.prodMethod == '先出品' && !ls.get('ISPAY_FIRST')) return router.back()
    if (tableInfo.value.prodMethod == '先出品') return router.back() // 如果是先出品 不要取消订单   （有下单）
    if (payData.value.length > 0) return router.back() // 如果有支付记录 不要取消订单  （有下单）
    if (waresData.value.length == 0) return router.back() // 如果待付商品为空 不要取消订单  
    if (loss.value) return router.back()  // 如果损赔 不要取消订单    
    if(ls.get("WARES_ORDER")) return router.back() // 如果本地购物车有数据（先买单点结账会保留本地购物车数据，下单成功或者离开支付页面都会清除数据） 不要取消订单（因为都没下订单）
    const todo = router.currentRoute.value.query.todo
    // if (todo && todo == 'orderAdd') {
    let detailList = []
    const details = PaymentRef.value.details
    
    // 处理勾选的商品
    if (details.length > 0) {
        // console.log('1 :>> ', 1);
        detailList = details
    } else {
        // console.log('2 :>> ', 2);
        detailList = multipleSelection.value.map(item => {
            if(item.subGoods && item.subGoods.length > 0){
                let arr = []
                arr = item.subGoods.map(v=>{
                    return v.itemCode
                })
                return arr
            }else{
                return item.itemCode
            }
            
        })
    }
    
    let payBatchCode = ""
    payData.value.forEach(item => {
        payBatchCode = item.payBatchCode
    })
    let data = {
        consumeCode: router.currentRoute.value.query.consumeCode,
        goodsItemCode: detailList.join(','),
        payBatchCode,
    }
    Api.Common.PcObjProcess.Do({ "functionName": "OrderPayClose", "orgCode": "0004", "contentData": data }).then(res => {
        console.log('点击关闭 撤销所有订单 res :>> ', res);
        router.back()
    }) 
}

const returnPayType12 = (params) => {
    PaymentRef.value.getTicket()
}


// 阻止F5刷新
const func1 = () => {
    window.addEventListener(
        "keydown",
        function (e) {
            if (
                e.key === "F5"
            ) {
                e.preventDefault();
            }
        },
        false
    );
};
// func1()
</script>

<style scoped lang="scss">
/* 在这里编写组件的CSS样式 */
.app-container {
    height: 100%;
    padding: 10px 100px 20px 100px;
    background: #F2F2F2;

    .table-info-row {
        width: 100%;
        display: flex;
        justify-content: space-between;

        .table-info {
            width: 1540px;
            height: 60px;
            background: #FFFFFF;
            border-radius: 8px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0 39px;
        }

        .back-btn {
            width: 120px;
            height: 60px;
            background: #CCCCCC;
            border-radius: 8px;
            font-size: 18px;
            color: #212121;
            border: 0px;
        }
    }

    .content-box {
        margin-top: 20px;
        display: flex;
    }
}

.font-size-16 {
    font-size: 16px;
}

.font-size-20 {
    font-size: 20px;
}

.font-weight-blod {
    font-weight: bold;
}

.font-weight-normal {
    font-weight: normal;
}

.color-212121 {
    color: #212121;
}

.color-666 {
    color: #666666;
}

.color-FF3333 {
    color: #FF3333;
}
</style>
